package com.lyh.servlet;

import com.lyh.pojo.Book;
import com.lyh.pojo.Category;
import com.lyh.service.BookService;
import com.lyh.service.CategoryService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.List;

/**
 * 功能
 * 作者：lyh
 * 日期：2024/8/8 15:30
 */
@WebServlet("/update")
@MultipartConfig //解析二进制表单
public class updateBook extends HttpServlet {
    BookService bookService = new BookService();
    CategoryService categoryService = new CategoryService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收参数
        String id = request.getParameter("id");
        String pageNum = request.getParameter("pageNum");
        //2.根据id查找员工信息
        Book book = bookService.findById(Integer.parseInt(id));
        //3.查找部门信息
        List<Category> categoryList = categoryService.findAllTypes();
        //4.保存数据 request域中
        request.setAttribute("book",book);
        request.setAttribute("categoryList",categoryList);
        request.setAttribute("pageNum",pageNum);
        //5.转发界面
        request.getRequestDispatcher("/jsp/updateBook.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收表单数据
        String id = request.getParameter("id");
        String pageNum = request.getParameter("pageNum");
        String bname = request.getParameter("bname");
        String author = request.getParameter("author");
        String num = request.getParameter("num");
        String price = request.getParameter("price");
        String cid = request.getParameter("cid");

        String page = request.getParameter("page");
        Part file2 = request.getPart("file1");
        //文件名称 保证名称不重复
        if (file2.getSize()>0){
            //获取当前时间的毫秒值
            page = System.currentTimeMillis()+".jpg";
            // new Date().getTime()
//            Calendar.getInstance().getTimeInMillis();
            //获取项目的输出目录 指定上传路径
            String realPath = getServletContext().getRealPath("/static/img");
            //执行上传操作
            file2.write(realPath+"/"+page);
        }
        //2.调用业务层方法完成添加
        bookService.updateBook(new Book(Integer.parseInt(id),bname,author,Integer.parseInt(num),page,Double.parseDouble(price),Integer.parseInt(cid)));
        //3.做出响应 重定向-》图书展示
//        response.sendRedirect(request.getContextPath()+"/show");
        response.sendRedirect(request.getContextPath()+"/show?pageNum="+pageNum);
    }
}
